package com.bkhc.common.util;

import com.alibaba.fastjson.JSONObject;
import com.bkhc.common.constant.RdisKeyContant;
import com.bkhc.common.entity.User;
import com.bkhc.common.permissions.bean.UserPermission;
import com.bkhc.common.vo.UserBean;
import org.springframework.http.HttpEntity;
import org.springframework.http.HttpHeaders;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpSession;
import java.util.List;


public class CommonUtil {

    public static UserBean getCrruentUser(){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession(false);
        if(session==null){
            return null;
        }
        Object obj = session.getAttribute(RdisKeyContant.USER_INFO_SESSION);
        if(obj==null){
            return null;
        }

        return JSONObject.parseObject(obj.toString(),UserBean.class);
    }

    public static UserPermission getCrruentUserPermission(String appName){
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession(false);
        if(session==null){
            return null;
        }
        Object obj = session.getAttribute(RdisKeyContant.USER_PERMISSION_SESSION+"_"+appName);
        if(obj==null){
            return null;
        }
        return  (UserPermission)obj;
    }

    public static Object getDataScope() {
        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpSession session = request.getSession(false);
        if(session==null){
            return null;
        }
        Object obj = session.getAttribute(RdisKeyContant.USER_DATASCOPE_SESSION);
        if(obj==null){
            return null;
        }
        return obj;
    }

    public static HttpEntity<Object> buildParam(Object obj){

        HttpServletRequest request = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        Cookie[] s = request.getCookies();
        HttpHeaders httpHeaders = new HttpHeaders();
        for(int i=0;i<s.length;i++){
            httpHeaders.set(s[i].getName(),s[i].getValue());

        }
        HttpEntity<Object> httpEntity = new HttpEntity<Object>(obj,httpHeaders);
        return httpEntity;
    }
}
